import Vue from 'vue'
import App from './App'
import VueRouter from 'vue-router'
import RouterConfig from './router-config'
import store from './store'
import VueResource from 'vue-resource'
import quillEditor from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import returnCode from './const/returnCode'

Vue.use(VueResource)
Vue.use(VueRouter)
Vue.use(quillEditor)

const router = new VueRouter({
  mode: 'hash',
  routes: RouterConfig
})

router.beforeEach(async (to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    let loginFlag = store.state.user.haveLogin
    if (!loginFlag) {
      console.log('not login')
      let res = await Vue.http.get('/user/check-login')
      if (parseInt(res.data.status) === returnCode.success) {
        let info = res.data.result
        store.dispatch('user/login', info)
      } else {
        console.log('tiaozhuan')
        next({
          path: '/index/login',
          query: { redirect: to.fullPath }
        })
      }
    } else {
      next()
    }
  } else {
    next() // 确保一定要调用 next()
  }
})

/* eslint-disable no-new */
new Vue({
  el: '#app',
  store,
  router: router,
  render: h => h(App)
})
